<!-- https://github.com/xyxiao001/vue-cropper?tab=readme-ov-file -->
<template>
    <el-dialog v-model="dialogVisible" title="头像更新" width="360" class="dialog-container">
        <div class="dialog-container-cropper">
            <vueCropper ref="cropper" 
            :img="option.img" 
            :outputType="option.outputType"
            :autoCrop="option.autoCrop"
            :autoCropWidth="option.autoCropWidth"
            :autoCropHeight="option.autoCropHeight">
            </vueCropper>
        </div>
        <div class="dialog-container-other-item">
            <label class="btn" for="uploads">选择图片</label>
            <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
                accept="image/png, image/jpeg, image/gif, image/jpg" @change="selectImg($event)">
            <button class="btn" @click="uploadImg">更新</button>
            <button class="btn" @click="downImg">下载</button>
        </div>

    </el-dialog>

</template>


<script setup lang="ts">
import 'vue-cropper/dist/index.css'
import {VueCropper} from "vue-cropper";
import { ref, reactive } from 'vue';
import { useUserStore } from '../store/useUserStore';
import request from '@/router/request'
import {ElMessage} from 'element-plus'
import type JsonResult from '@/interfaces/JsonResult'

const userStore = useUserStore()
// 裁剪机属性
const option = reactive({
    img: "#",
    outputType: 'png',
    autoCrop: true,
    autoCropWidth: '120',
    autoCropHeight: '120'
})

// 弹框控制
const dialogVisible = ref(false)
const cropper = ref()

//下载图片
const downImg = ()=>{
    var aLink = document.createElement('a');
    aLink.download = 'dyz';
    cropper.value.getCropData((data:any)=>{
        aLink.href = data;
        aLink.click();
    })
}

//上传图片
const uploadImg = ()=>{
    cropper.value.getCropBlob(async (data:any)=>{
        try{
            const formData = new FormData()
            formData.append("file",data)
            const response:JsonResult = await request.post("/resource/file/avatar/update",formData)
            if(response.state==200){
                ElMessage.success("更新成功")
                userStore.user.avatar = response.data
            }else{
                ElMessage.warning(response.message)
            }
        }catch(error:any){
            ElMessage.error(error)
        }
    })
}

// 选择图片
const selectImg = (e: any) => {
    // 从事件对象e中获取触发事件的元素（比如<input type="file">）的files数组中的第一个文件
    let file = e.target.files[0];
    if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        console.log("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种")
        return false
    }
    // 创建一个FileReader对象，用于读取文件内容
    let reader = new FileReader();
    // 当FileReader读取文件完成时，会触发onload事件，并执行这个回调函数
    reader.onload = (e: any) => {
        let data;
        if (typeof e.target.result === 'object') {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
            data = e.target.result;
        }
        option.img = data;
    };
    // 转化为base64
    // reader.readAsDataURL(file)
    // 转化为blob
    // 读取文件内容为ArrayBuffer。这通常用于处理二进制数据，如图片、视频等。
    reader.readAsArrayBuffer(file);
}


defineExpose({ dialogVisible })
</script>


<style scoped>
.dialog-container {
    display: flex;
}

.dialog-container-cropper {
    width: 100%;
    height: 180px;
}

.dialog-container-other-item {
    display: flex;
    justify-content: center;
}
.btn {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #c0ccda;
    color: #1f2d3d;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin:20px 10px 0px 0px;
    padding: 9px 15px;
    font-size: 14px;
    border-radius: 4px;
    color: #fff;
    background-color: #50bfff;
    border-color: #50bfff;
    transition: all .2s ease;
    text-decoration: none;
    user-select: none;
}
</style>